<template>
  <div class="chart-container">
    <div ref="barChart" class="chart-item"></div>
    <div ref="pieChart" class="chart-item"></div>
  </div>
</template>

<script>
// 引入echarts
import * as echarts from 'echarts';

export default {
  name: 'ChartDemo',
  mounted() {
    this.initBarChart();
    this.initPieChart();
  },
  beforeDestroy() {
    // 销毁图表实例，避免内存泄漏
    if (this.barChart) {
      this.barChart.dispose();
    }
    if (this.pieChart) {
      this.pieChart.dispose();
    }
  },
  methods: {
    initBarChart() {
      // 初始化柱状图
      this.barChart = echarts.init(this.$refs.barChart);
      const option = {
        title: {
          text: '柱状图示例'
        },
        tooltip: {},
        xAxis: {
          data: ['A', 'B', 'C', 'D', 'E', 'F']
        },
        yAxis: {},
        series: [{
          name: '销量',
          type: 'bar',
          data: [5, 20, 36, 10, 10, 20]
        }]
      };
      this.barChart.setOption(option);
    },
    initPieChart() {
      // 初始化饼状图
      this.pieChart = echarts.init(this.$refs.pieChart);
      const option = {
        title: {
          text: '饼状图示例'
        },
        tooltip: {
          trigger: 'item'
        },
        series: [{
          name: '访问来源',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 1048, name: '搜索引擎' },
            { value: 735, name: '直接访问' },
            { value: 580, name: '邮件营销' },
            { value: 484, name: '联盟广告' },
            { value: 300, name: '视频广告' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      this.pieChart.setOption(option);
    }
  }
}
</script>

<style scoped>
.chart-container {
  display: flex;
  width: 100%;
  height: 500px;
}

.chart-item {
  flex: 1;
  margin: 10px;
}
</style>